const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const path = require('path')
const nunjucks = require('nunjucks')                                //引入模板引擎
console.log(process.env.NODE_ENV)
// const Router = require('./routers')                              //导入后端路由
const Api = require('./api')                                        //导入API
const { success, error } = require('./middleware/response')         //导入处理函数
const { errorlog } = require('./middleware/log')                    //导入错误日志
const requestLog = require('./middleware/requestLog')
const jwtVerify = require('./middleware/jwtVerify')


app.use(bodyParser.urlencoded({ extende: true }))                   //配置解析post请求
app.use(bodyParser.json())

app.set('view engine', 'html')
app.set('views', path.resolve(__dirname, './views'))
app.use(express.static(path.join(__dirname, 'public')))
nunjucks.configure('views', { autoescape: true, express: app })     //配置nunjucks模板引擎

app.use(requestLog)                                                 //请求日志输出
app.use(success)                                                    //注入成功响应
app.use(error)                                                      //注入失败响应
app.use(jwtVerify)                                                  //注入jwt验证
app.use(Api)                                                        //注入API
// app.use(Router)                                                  //注入后端路由(目前不做后端路由)
app.get('*', (req, res) => {
  res.render('index')
})

app.use(errorlog)                                                   //错误日志记录
//响应信息
app.use((err, req, res, next) => {
  res.error('服务器正忙!', 500, null)
})

app.listen(3000, () => {
  console.log('http://localhost:3000')
})
